<template>
  <div class="voice-complaint-container">
    <!-- 左侧历史记录面板 -->
    <div class="history-panel">
      <div class="recent-recording">
        <h4>最近一次录音</h4>
        <div v-if="lastRecording" class="recording-item">
          <div class="recording-text">{{ lastRecording.text }}</div>
          <div class="recording-meta">
            <span>{{ lastRecording.time }}</span>
            <el-button 
              size="mini" 
              type="text" 
              @click="playRecording(lastRecording)"
              :icon="isPlaying && currentPlaying === lastRecording.id ? 'el-icon-video-pause' : 'el-icon-video-play'"
            ></el-button>
          </div>
        </div>
        <div v-else class="empty-tip">暂无录音记录</div>
      </div>
      
      <div class="history-table">
        <h4>历史录音记录</h4>
        <el-table
          :data="historyRecordings"
          height="300"
          style="width: 100%"
          size="mini"
          @row-click="handleRowClick"
        >
          <el-table-column
            prop="text"
            label="内容"
            width="180"
            :show-overflow-tooltip="true"
          >
            <template #default="{row}">
              <span class="text-ellipsis">{{ row.text || '无文本内容' }}</span>
            </template>
          </el-table-column>
          <el-table-column
            prop="time"
            label="时间"
            width="100"
          />
          <el-table-column
            label="操作"
            width="80"
          >
            <template #default="{row}">
              <el-button 
                size="mini" 
                type="text" 
                @click.stop="playRecording(row)"
                :icon="isPlaying && currentPlaying === row.id ? 'el-icon-video-pause' : 'el-icon-video-play'"
              ></el-button>
              <el-button 
                size="mini" 
                type="text" 
                @click.stop="deleteRecording(row)"
                icon="el-icon-delete"
              ></el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 右侧录音控制面板 -->
    <div class="control-panel">
      <div class="voice-recorder">
        <!-- 状态指示器 -->
        <div class="status-indicator">
          <i class="el-icon-wifi" :style="{color: statusColor}"></i>
          <span class="status-text">{{ statusText }}</span>
        </div>
        
        <!-- 录音按钮 -->
        <div class="recorder-icon" @click="toggleRecording">
          <i :class="['el-icon-microphone', {'pulse': recording, 'recording-active': recording}]" 
             :style="{color: recording ? 'red' : '#409EFF'}"></i>
        </div>
        
        <!-- 语言选择 -->
        <div class="language-selector">
          <el-select 
            v-model="selectedLanguage" 
            size="mini" 
            placeholder="选择语言"
            style="width: 140px"
            :disabled="recording"
          >
            <el-option
              v-for="lang in languages"
              :key="lang.value"
              :label="lang.label"
              :value="lang.value">
            </el-option>
          </el-select>
        </div>

        <!-- 录音时长显示 -->
        <div v-if="recording" class="recording-timer">
          录音中: {{ formatTime(recordingTime) }}
        </div>
		
		<!-- 新增录音控制按钮组 -->
		<div class="recording-controls">
		    <el-button 
		      v-if="!recording"
		      size="mini" 
		      type="primary" 
		      @click="startRecording"
		      icon="el-icon-microphone"
		    >
		      开始录音
		    </el-button>
		    
		    <template v-else>
		      <el-button 
		        size="mini" 
		        @click="pauseRecording"
		        :disabled="isPaused"
		        icon="el-icon-video-pause"
		      >
		        暂停
		      </el-button>
		      <el-button 
		        size="mini" 
		        @click="resumeRecording"
		        :disabled="!isPaused"
		        icon="el-icon-video-play"
		      >
		        继续
		      </el-button>
		      <el-button 
		        size="mini" 
		        type="success" 
		        @click="finishRecording"
		        icon="el-icon-check"
		      >
		        完成
		      </el-button>
		    </template>
		  </div>
      </div>
      
      <div class="transcription-result">
        <el-input
          type="textarea"
          :rows="4"
          v-model="transcriptionText"
          placeholder="语音识别结果将显示在这里"
          readonly
        ></el-input>
        <div class="action-buttons">
          <el-button 
            size="small" 
            type="primary" 
            @click="confirmTranscription"
            :disabled="!transcriptionText"
            icon="el-icon-check"
          >
            确认使用
          </el-button>
          <el-button 
            size="small" 
            @click="clearTranscription"
            :disabled="!transcriptionText"
            icon="el-icon-delete"
          >
            清空内容
          </el-button>
          <el-button 
            size="small" 
            @click="saveToLocal"
            :disabled="!transcriptionText"
            icon="el-icon-download"
          >
            保存本地
          </el-button>
        </div>
      </div>
    </div>

    <!-- 隐藏的音频播放器 -->
    <audio ref="audioPlayer" style="display: none" @ended="onAudioEnd"></audio>
  </div>
</template>

<script>
// import RecordRTC from 'recordrtc';

export default {
  name: 'VoiceComplaints',
  props: {
    value: String,
    patientId: [String, Number]
  },
  data() {
    return {
      // 语音识别状态
      recording: false,
      transcriptionText: this.value || '',
      volumeLevel: 0,
      status: 'idle',
      recordingTime: 0,
      recordingTimer: null,
      
      // 语言配置
      selectedLanguage: 'zh-CN',
      languages: [
        { label: '中文(普通话)', value: 'zh-CN' },
        { label: '中文(粤语)', value: 'zh-HK' },
        { label: '英文(美国)', value: 'en-US' },
        { label: '日文', value: 'ja-JP' }
      ],
      
      // 音频处理
      audioContext: null,
      mediaRecorder: null,
      audioChunks: [],
      speechRecognizer: null,
      
	  // 新增录音状态
	  isPaused: false,
		
      // 历史记录
      lastRecording: null,
      historyRecordings: [],
      
      // 播放状态
      isPlaying: false,
      currentPlaying: null
    }
  },
  computed: {
    statusColor() {
      const colors = {
        idle: '#909399',
        listening: this.volumeLevel > 3 ? '#67C23A' : '#F56C6C',
        processing: '#409EFF',
        error: '#F56C6C',
        success: '#67C23A'
      };
      return colors[this.status];
    },
    statusText() {
      const texts = {
        idle: '点击麦克风开始录音',
        listening: this.volumeLevel > 3 ? 
          '识别中...' : 
          '声音偏小，请靠近麦克风说话',
        processing: '语音识别处理中...',
        error: '识别失败，请重试',
        success: '识别成功'
      };
      return texts[this.status];
    },
    isSpeechRecognitionSupported() {
      return 'webkitSpeechRecognition' in window || 'SpeechRecognition' in window;
    }
  },
  mounted() {
    this.loadHistory();
    this.initAudioContext();
  },
  beforeDestroy() {
    this.cleanupResources();
  },
  methods: {
    // 检查浏览器支持
    checkBrowserSupport() {
        // 检查是否在安全环境下
        const isSecureOrigin = 
			location.protocol === 'https:' || 
			location.hostname === 'localhost' || 
			location.hostname === '10.10.10.179' || 
			location.hostname === '10.10.10.151' || 
			location.hostname === '10.10.10.165' || 
			location.hostname === '127.0.0.1';
        
        if (!isSecureOrigin) {
          this.$message.warning('录音功能需要在HTTPS或localhost环境下使用');
          return false;
        }
        
        // 检查语音识别支持
        const isSpeechSupported = 'webkitSpeechRecognition' in window || 
                                 'SpeechRecognition' in window;
        
        // 检查媒体设备支持
        const isMediaSupported = !!(navigator.mediaDevices?.getUserMedia) ||
                                !!navigator.webkitGetUserMedia || 
                                !!navigator.mozGetUserMedia ||
                                !!navigator.msGetUserMedia;
        
        if (!isSpeechSupported) {
          this.$message.error('您的浏览器不支持语音识别功能，请使用Chrome或Edge浏览器');
          return false;
        }
        
        if (!isMediaSupported) {
          this.$message.error('您的浏览器不支持录音功能');
          return false;
        }
        
        return true;
      },
    
	// 新增录音控制方法
	async pauseRecording() {
	    try {
	      if (this.mediaRecorder && this.mediaRecorder.state === 'recording') {
	        // 暂停录音
	        this.mediaRecorder.pauseRecording();
	        this.isPaused = true;
	        this.status = 'paused';
	        
	        // 暂停语音识别
	        if (this.speechRecognizer) {
	          this.speechRecognizer.abort(); // 使用abort而不是stop
	        }
	        
	        // 暂停计时器
	        this.stopRecordingTimer();
	        
	        // 暂停音量检测
	        this.stopVolumeDetection();
	        
	        this.$message.info('录音已暂停');
	      }
	    } catch (error) {
	      console.error('暂停录音失败:', error);
	      this.$message.error('暂停录音失败: ' + error.message);
	    }
	},
	
	// 优化后的 resumeRecording 方法
	async resumeRecording() {
	    try {
	      if (this.mediaRecorder && this.mediaRecorder.state === 'paused') {
	        // 继续录音
	        this.mediaRecorder.resumeRecording();
	        this.isPaused = false;
	        this.status = 'listening';
	        
	        // 重新初始化语音识别
	        if (this.speechRecognizer) {
	          const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
	          this.speechRecognizer = new SpeechRecognition();
	          this.speechRecognizer.lang = this.selectedLanguage;
	          this.speechRecognizer.interimResults = true;
	          this.speechRecognizer.continuous = true;
	          
	          this.speechRecognizer.onresult = (event) => {
	            let interimTranscript = '';
	            let finalTranscript = '';
	            
	            for (let i = event.resultIndex; i < event.results.length; i++) {
	              const transcript = event.results[i][0].transcript;
	              if (event.results[i].isFinal) {
	                finalTranscript += transcript;
	              } else {
	                interimTranscript += transcript;
	              }
	            }
	            
	            this.transcriptionText = finalTranscript || interimTranscript;
	          };
	          
	          this.speechRecognizer.start();
	        }
	        
	        // 恢复计时器
	        this.startRecordingTimer();
	        
	        // 恢复音量检测
	        this.startVolumeDetection();
	        
	        this.$message.success('录音已继续');
	      }
	    } catch (error) {
	      console.error('继续录音失败:', error);
	      this.$message.error('继续录音失败: ' + error.message);
	    }
	  },
	
	// 优化后的 finishRecording 方法
	async finishRecording() {
	  try {
		// 停止录音
		await this.stopRecording();
		
		// 确保录音数据已处理
		if (this.mediaRecorder) {
		  const blob = this.mediaRecorder.getBlob();
		  
		  // 上传录音文件
		  await this.uploadRecording(blob);
		  
		  // 本地保存录音记录
		  this.lastRecording = {
			id: Date.now(),
			text: this.transcriptionText,
			time: this.formatDateTime(new Date()),
			audioUrl: URL.createObjectURL(blob),
			audioBlob: blob
		  };
		  
		  this.historyRecordings.unshift(this.lastRecording);
		}
		
		if (this.transcriptionText) {
		  this.$message.success('录音已完成并上传');
		} else {
		  this.$message.warning('录音已完成，但未识别到语音内容');
		}
	  } catch (error) {
		console.error('完成录音失败:', error);
		this.$message.error('完成录音失败');
	  }
	},
	
	// 新增的上传录音方法
	async uploadRecording(audioBlob) {
	  try {
		// 检查音频数据有效性
		if (!audioBlob || audioBlob.size === 0) {
		  throw new Error('无效的音频数据');
		}
		
		// 准备表单数据
		const formData = new FormData();
		formData.append('file', audioBlob, `recording_${Date.now()}.wav`);
		formData.append('patientId', this.patientId);
		formData.append('text', this.transcriptionText);
		formData.append('language', this.selectedLanguage);
		formData.append('duration', this.recordingTime);
		
		// 调用上传接口
		const response = await this.$api.uploadFile(formData);
		
		if (response.success) {
		  this.$message.success('录音文件上传成功');
		  return response.data; // 返回服务器返回的数据
		} else {
		  throw new Error(response.message || '上传失败');
		}
	  } catch (error) {
		console.error('上传录音失败:', error);
		this.$message.error('上传录音失败: ' + error.message);
		throw error;
	  }
	},
	
	// 新增的 toggleRecording 方法
	async toggleRecording() {
	  if (this.recording) {
		await this.stopRecording();
	  } else {
		await this.startRecording();
	  }
	},
		
    // 初始化音频上下文
    async initAudioContext() {
      try {
        this.audioContext = new (window.AudioContext || window.webkitAudioContext)();
      } catch (error) {
        console.error('音频上下文初始化失败:', error);
      }
    },

    // 加载历史记录
    async loadHistory() {
      try {
        // 这里应该调用API获取历史记录
        const response = await this.$api.getVoiceHistory({
          patientId: this.patientId,
          days: 30
        });
        
        this.historyRecordings = response.data;
        this.lastRecording = this.historyRecordings[0];
      } catch (error) {
        console.warn('加载历史记录失败，使用模拟数据');
        // 模拟数据
        this.historyRecordings = [
          { 
            id: 1, 
            text: '患者主诉胃部不适，伴有轻微疼痛', 
            time: this.formatDateTime(new Date(Date.now() - 86400000)), 
            audioUrl: '' 
          },
          { 
            id: 2, 
            text: '头晕目眩，站立时症状加重', 
            time: this.formatDateTime(new Date(Date.now() - 172800000)), 
            audioUrl: '' 
          }
        ];
        this.lastRecording = this.historyRecordings[0];
      }
    },

    // 开始录音
    async startRecording() {
	  if (!this.checkBrowserSupport()) return;
	  
	  try {
		this.status = 'listening';
		this.recording = true;
		this.isPaused = false;
		this.audioChunks = [];
		this.recordingTime = 0;
		this.transcriptionText = '';
		
		// 获取麦克风权限
		const stream = await this.getUserMediaStream();
		
		// 初始化语音识别
		await this.initSpeechRecognition(stream);
		
		// 初始化录音器
		this.mediaRecorder = new RecordRTC(stream, {
		  type: 'audio',
		  mimeType: 'audio/wav',
		  recorderType: RecordRTC.StereoAudioRecorder,
		  sampleRate: 16000,
		  numberOfAudioChannels: 1,
		  disableLogs: true,
		  timeSlice: 250,
		  ondataavailable: (blob) => {
			this.audioChunks.push(blob);
		  }
		});
		
		this.mediaRecorder.startRecording();
		this.startRecordingTimer();
		
		this.$message.success('录音已开始');
	  } catch (error) {
		this.handleRecordingError(error);
	  }
	},
    
	// 优化后的 getUserMediaStream 方法
	  async getUserMediaStream() {
	    try {
	      const constraints = {
	        audio: {
	          sampleRate: 16000,
	          channelCount: 1,
	          echoCancellation: true,
	          noiseSuppression: true,
	          autoGainControl: true
	        }
	      };
	      
	      // 兼容不同浏览器的getUserMedia实现
	      if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
	        return await navigator.mediaDevices.getUserMedia(constraints);
	      } else if (navigator.webkitGetUserMedia) {
	        return await new Promise((resolve, reject) => {
	          navigator.webkitGetUserMedia(constraints, resolve, reject);
	        });
	      } else {
	        throw new Error('浏览器不支持获取用户媒体');
	      }
	    } catch (error) {
	      console.error('获取麦克风权限失败:', error);
	      throw error;
	    }
	  },
	  
    // 初始化语音识别
	async initSpeechRecognition(stream) {
	    return new Promise((resolve, reject) => {
	      const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition;
	      
	      if (!SpeechRecognition) {
	        reject(new Error('浏览器不支持语音识别'));
	        return;
	      }
	      
	      this.speechRecognizer = new SpeechRecognition();
	      
	      // 配置识别器
	      this.speechRecognizer.lang = this.selectedLanguage;
	      this.speechRecognizer.interimResults = true;
	      this.speechRecognizer.continuous = true;
	      
	      // 识别结果处理
	      this.speechRecognizer.onresult = (event) => {
	        let interimTranscript = '';
	        let finalTranscript = '';
	        
	        for (let i = event.resultIndex; i < event.results.length; i++) {
	          const transcript = event.results[i][0].transcript;
	          if (event.results[i].isFinal) {
	            finalTranscript += transcript + ' ';
	          } else {
	            interimTranscript += transcript;
	          }
	        }
	        
	        // 更新识别结果
	        this.transcriptionText = finalTranscript || interimTranscript;
	      };
	      
	      this.speechRecognizer.onerror = (event) => {
	        // 忽略no-speech和网络错误
	        if (event.error === 'no-speech') {
	          console.log('未检测到语音输入');
	          return;
	        }
	        
	        if (event.error !== 'network') {
	          console.error('语音识别错误:', event.error);
	          this.status = 'error';
	          this.$message.error(`语音识别错误: ${event.error}`);
	        }
	      };
	      
	      this.speechRecognizer.onend = () => {
	        if (this.recording && !this.isPaused) {
	          // 如果仍在录音状态且未暂停，重新启动识别
	          this.speechRecognizer.start();
	        }
	      };
	      
	      // 设置音量检测
	      const source = this.audioContext.createMediaStreamSource(stream);
	      this.analyser = this.audioContext.createAnalyser();
	      this.analyser.fftSize = 32;
	      source.connect(this.analyser);
	      this.startVolumeDetection();
	      
	      // 开始识别
	      this.speechRecognizer.start();
	      resolve();
	    });
	  },

    // 停止录音
    async stopRecording() {
        try {
          if (this.mediaRecorder && 
              (this.mediaRecorder.state === 'recording' || 
               this.mediaRecorder.state === 'paused')) {
            
            // 停止语音识别
            if (this.speechRecognizer) {
              this.speechRecognizer.stop();
            }
            
            // 停止录音并获取最终数据
            let finalBlob = null;
            await new Promise((resolve) => {
              this.mediaRecorder.stopRecording(() => {
                try {
                  finalBlob = this.mediaRecorder.getBlob();
                  if (finalBlob && finalBlob.size > 0) {
                    this.audioChunks.push(finalBlob);
                  }
                } catch (error) {
                  console.error('获取录音数据失败:', error);
                }
                resolve();
              });
            });
            
            this.recording = false;
            this.isPaused = false;
            this.stopRecordingTimer();
            this.stopVolumeDetection();
            
            // 关闭音频流
            if (this.mediaRecorder.stream) {
              this.mediaRecorder.stream.getTracks().forEach(track => track.stop());
            }
            
            // 处理录音结果
            if (finalBlob && finalBlob.size > 0) {
              await this.handleRecordingStop(finalBlob);
            } else {
              this.$message.warning('未获取到有效的录音数据');
            }
          }
        } catch (error) {
          console.error('停止录音失败:', error);
          this.$message.error('停止录音失败: ' + error.message);
        }
      },

    // 处理录音停止
    async handleRecordingStop(audioBlob) {
        try {
          this.status = 'processing';
          
          // 确保音频数据有效
          if (!audioBlob || audioBlob.size === 0) {
            throw new Error('无效的音频数据');
          }
          
          // 保存录音记录
          await this.saveRecording(this.transcriptionText, audioBlob);
          
          this.status = 'success';
          this.$message.success('语音识别完成');
          
        } catch (error) {
          console.error('语音识别失败:', error);
          this.status = 'error';
          this.$message.error('语音识别处理失败: ' + error.message);
        }
      },

    // 保存录音记录
    async saveRecording(text, audioBlob) {
		if (audioBlob.size > 10 * 1024 * 1024) { // 10MB限制
  this.$message.warning('录音文件过大，无法保存');
  return;
}
        try {
          // 检查音频数据有效性
          if (!audioBlob || audioBlob.size === 0) {
            throw new Error('无效的音频数据');
          }
          
          // 创建ObjectURL
          let audioUrl;
          try {
            audioUrl = URL.createObjectURL(audioBlob);
          } catch (error) {
            console.error('创建ObjectURL失败:', error);
            throw new Error('无法创建音频URL');
          }
          
          // 本地保存录音记录
          const newRecording = {
            id: Date.now(),
            text: text || '无识别内容',
            time: this.formatDateTime(new Date()),
            audioUrl: audioUrl,
            audioBlob: audioBlob
          };
          
          this.lastRecording = newRecording;
          this.historyRecordings.unshift(newRecording);
          
          // 保存到本地存储
          this.saveToLocalStorage(newRecording);
          
        } catch (error) {
          console.error('保存录音记录失败:', error);
          this.$message.warning('录音记录保存失败: ' + error.message);
        }
      },
	
	// 新增 saveToLocalStorage 方法
	  saveToLocalStorage(recording) {
	    try {
	      // 获取现有记录
	      const storedRecordings = JSON.parse(localStorage.getItem('voiceRecordings') || '[]');
	      
	      // 添加新记录（不存储Blob，因为无法直接序列化）
	      storedRecordings.unshift({
	        id: recording.id,
	        text: recording.text,
	        time: recording.time
	      });
	      
	      // 保存回本地存储
	      localStorage.setItem('voiceRecordings', JSON.stringify(storedRecordings));
	      
	    } catch (error) {
	      console.error('本地存储失败:', error);
	    }
	},
    // 播放录音
    async playRecording(recording) {
      try {
        if (this.isPlaying && this.currentPlaying === recording.id) {
          // 暂停播放
          this.audioPlayer.pause();
          this.isPlaying = false;
          this.currentPlaying = null;
          return;
        }
        
        if (recording.audioUrl) {
          this.audioPlayer.src = recording.audioUrl;
          await this.audioPlayer.play();
          this.isPlaying = true;
          this.currentPlaying = recording.id;
        } else {
          this.$message.warning('该录音没有音频文件');
        }
      } catch (error) {
        console.error('播放失败:', error);
        this.$message.error('音频播放失败');
      }
    },

    // 音频播放结束
    onAudioEnd() {
      this.isPlaying = false;
      this.currentPlaying = null;
    },

    // 删除录音记录
    async deleteRecording(recording) {
      try {
        await this.$api.deleteVoiceRecording(recording.id);
        this.historyRecordings = this.historyRecordings.filter(r => r.id !== recording.id);
        if (this.lastRecording && this.lastRecording.id === recording.id) {
          this.lastRecording = this.historyRecordings[0] || null;
        }
        this.$message.success('删除成功');
      } catch (error) {
        console.error('删除失败:', error);
        this.$message.error('删除失败');
      }
    },

    // 表格行点击
    handleRowClick(row) {
      this.transcriptionText = row.text;
    },

    // 开始录音计时器
    startRecordingTimer() {
      this.recordingTimer = setInterval(() => {
        this.recordingTime++;
        // 添加5分钟限制
        if (this.recordingTime >= 300) {
          this.$message.warning('录音时间过长，自动停止');
          this.stopRecording();
        }
      }, 1000);
    },

    // 停止录音计时器
    stopRecordingTimer() {
      if (this.recordingTimer) {
        clearInterval(this.recordingTimer);
        this.recordingTimer = null;
      }
    },
    
    // 开始音量检测
    startVolumeDetection() {
      this.volumeCheckInterval = setInterval(() => {
        const dataArray = new Uint8Array(this.analyser.frequencyBinCount);
        this.analyser.getByteFrequencyData(dataArray);
        const sum = dataArray.reduce((a, b) => a + b, 0);
        this.volumeLevel = Math.min(5, Math.max(1, Math.floor(sum / dataArray.length / 20)));
      }, 100);
    },
    
    // 停止音量检测
    stopVolumeDetection() {
      if (this.volumeCheckInterval) {
        clearInterval(this.volumeCheckInterval);
        this.volumeCheckInterval = null;
        this.volumeLevel = 0;
      }
    },

    // 格式化时间显示
    formatTime(seconds) {
      const mins = Math.floor(seconds / 60);
      const secs = seconds % 60;
      return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    },
    
    // 格式化日期时间
    formatDateTime(date) {
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit'
      }).replace(/\//g, '-');
    },

    // 确认转录文本
    async confirmTranscription() {
        try {
          if (!this.transcriptionText) {
            this.$message.warning('没有可确认的录音内容');
            return;
          }
          
          // 查找最近一次录音的Blob数据
          const recording = this.lastRecording || 
                          this.historyRecordings.find(r => r.text === this.transcriptionText);
          
          if (!recording || !recording.audioBlob) {
            this.$message.error('找不到对应的录音数据');
            return;
          }
          
          // 准备表单数据
          const formData = new FormData();
          formData.append('audio', recording.audioBlob);
          formData.append('text', this.transcriptionText);
          formData.append('language', this.selectedLanguage);
          formData.append('patientId', this.patientId);
          
          // 调用API保存
          const response = await this.$api.saveVoiceRecording(formData);
          
          // 更新录音记录的ID为服务器返回的ID
          if (response.data && response.data.id) {
            if (this.lastRecording && this.lastRecording.text === this.transcriptionText) {
              this.lastRecording.id = response.data.id;
            }
            
            const historyItem = this.historyRecordings.find(r => r.text === this.transcriptionText);
            if (historyItem) {
              historyItem.id = response.data.id;
            }
          }
          
          this.$emit('input', this.transcriptionText);
          this.$emit('confirm', this.transcriptionText);
          this.$message.success('语音内容已确认并保存');
          
        } catch (error) {
          console.error('确认录音失败:', error);
          this.$message.error('确认录音失败: ' + error.message);
        }
      },

    // 清空文本
    clearTranscription() {
      this.transcriptionText = '';
    },

    // 保存到本地
    saveToLocal() {
      const blob = new Blob([this.transcriptionText], { type: 'text/plain' });
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = `语音记录_${new Date().getTime()}.txt`;
      a.click();
      URL.revokeObjectURL(url);
    },

    // 清理资源
    cleanupResources() {
      this.stopRecording();
      this.stopRecordingTimer();
      this.stopVolumeDetection();
      
      // 清理Blob URL
      this.historyRecordings.forEach(recording => {
        if (recording.audioUrl && recording.audioUrl.startsWith('blob:')) {
          URL.revokeObjectURL(recording.audioUrl);
        }
      });
    }
  }
}
</script>

<style scoped>
.voice-complaint-container {
  display: flex;
  height: 100%;
  gap: 20px;
}

/* 左侧历史记录面板 */
.history-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  border-right: 1px solid #ebeef5;
  padding-right: 20px;
}

.recent-recording, .history-table {
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.recent-recording h4, .history-table h4 {
  margin: 0 0 10px 0;
  color: #606266;
  font-size: 14px;
}

.recording-item {
  padding: 8px;
  border: 1px solid #ebeef5;
  border-radius: 4px;
}

.recording-text {
  margin-bottom: 8px;
  font-size: 13px;
  line-height: 1.5;
  color: #303133;
}

.recording-meta {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 12px;
  color: #909399;
}

.empty-tip {
  color: #c0c4cc;
  font-size: 12px;
  text-align: center;
  padding: 20px 0;
}

/* 右侧控制面板 */
.control-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.voice-recorder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 20px;
  background: #fff;
  border-radius: 4px;
  margin-bottom: 15px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
  position: relative;
  height: 200px;
}

.recording-controls {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
  transition: all 0.3s ease;
}
.status-indicator {
  position: absolute;
  top: 15px;
  display: flex;
  align-items: center;
  gap: 5px;
}

.status-indicator i {
  font-size: 18px;
}

.status-text {
  font-size: 12px;
  color: #606266;
}
/* 更新状态颜色 */
.status-paused {
  color: #E6A23C;
}
/* 更新样式 */
.recorder-icon {
  cursor: default; /* 移除点击效果 */
}

.recorder-icon i {
  font-size: 48px;
  transition: all 0.3s;
}

.recorder-icon i.pulse {
  animation: pulse 1.5s infinite;
}

.recorder-icon i.recording-active {
  color: red;
}

.language-selector {
  margin-top: 10px;
}

.recording-timer {
  margin-top: 10px;
  font-size: 12px;
  color: #606266;
}

.transcription-result {
  flex: 1;
  background: #fff;
  padding: 15px;
  border-radius: 4px;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
}

.action-buttons {
  margin-top: 10px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.text-ellipsis {
  display: inline-block;
  max-width: 180px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

@keyframes pulse {
  0% { opacity: 1; }
  50% { opacity: 0.5; }
  100% { opacity: 1; }
}
</style>